/**
 * axios接口使用tips
 * baseApi： 在config.js内配置的url为本地请求的baseUrl
 * needOperator： 目前本地的接口除了get请求默认加了operator操作人，不需要的设置其为false，避免在formdata的传输等特殊情况下无法进行
 * isResponseHandle： 是否直接返回完整的返回值进行单独处理
 */
import axios from 'axios'
import encryptHandler from './encryptHandler'
import responseHandler from './responseHandler'
import loadingHandler from './loadingHandler'
import baseUrlHandler from './baseUrlHandler'
const handlers = [
  encryptHandler,
  baseUrlHandler,
  loadingHandler,
  responseHandler
]
function normalRequestResolve(config) {
  return config
}

function normalResponseResolve(response) {
  return response
}

function normalReject(error) {
  return Promise.reject(error)
}
const initHandler = Vue => {
  handlers.forEach(handler => {
    const handlerContext = handler(Vue)
    const {
      requestResolve = normalRequestResolve,
      requestReject = normalReject,
      responseResolve = normalResponseResolve,
      responseReject = normalReject
    } = handlerContext
    axios.interceptors.request.use(requestResolve, requestReject)
    axios.interceptors.response.use(responseResolve, responseReject)
  })
}
export default {
  install(Vue) {
    initHandler(Vue)
    // 绑定axios
    Vue.ajax = Vue.prototype.$ajax = axios

    // 添加rest-api方法
    Vue.rest = Vue.prototype.$rest = {
      request(config) {
        return axios.request(config)
      },
      get(path, config) {
        return axios.get(path, config)
      },
      post(path, data, config) {
        return axios.post(path, data, config)
      },
      put(path, data, config) {
        return axios.put(path, data, config)
      },
      delete(path, config) {
        return axios.delete(path, config)
      }
    }
  }
}
